package com.wenchao.app;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.example.x6.serial.SerialPort;
import com.wenchao.app.databinding.ActivitySerialPortBinding;
import com.wenchao.serialport.ByteUtils;
import com.wenchao.serialport.SerialPortService;

/**
 * @author zhangwenchao
 */
public class SerialPortActivity extends AppCompatActivity {

    private ActivitySerialPortBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivitySerialPortBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        SerialPortService.startService(this, "/dev/ttyXRUSB0", 115200);

        MyReceiver myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter(SerialPortService.RECEIVER_ACTION_NAME);
        registerReceiver(myReceiver, intentFilter);

        binding.btnSendData.setOnClickListener(v -> {
            SerialPort serialPort = SerialPortService.getSerialPort();
            if (serialPort != null) {
                serialPort.writeData(new byte[]{0x01, 0x02, 0x03, 0x04});
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    static class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            byte[] data = intent.getByteArrayExtra("data");
            Log.e("MyReceiver", ByteUtils.bytesToHexString(data));
        }
    }

}